# coding=utf-8

import re, urllib.request, time, _thread

def requestUrl(idx, url, threadName):
    try:
        urllib.request.urlopen(url)
    except BaseException as e:
        print('Error: 待 18 秒后，继续尝试 ' + threadName + ' -- ' + str(idx) + ' -- ' + url + ': ' + str(e))
        time.sleep(18)
        requestUrl(idx, url, threadName)

def requestList(urlList, startIdx, step, threadName):
    for idx, url in enumerate(urlList):
        if idx < startIdx or (idx - startIdx) % step != 0:
            continue

        # Url 替换为 Nexus 的路径
        nurl = url.replace('https://updates.jenkins.io/download/', 'http://localhost:8081/repository/jenkins/')
        print(threadName + ' -- ' + str(idx) + ' -- ' + nurl)
        requestUrl(idx, nurl, threadName)
        time.sleep(1)

    print(threadName + '============= 执行完成！！！')

# 读取文件内容
file1 = open('../update-center.json', 'r', encoding='utf-8')
txt = file1.read()

# 正则匹配 URL
links = re.findall('"url":"(\S*.hpi)"', txt)

try:
    _thread.start_new_thread(requestList, (links, 0, 3, 'thread-1'))
    _thread.start_new_thread(requestList, (links, 1, 3, 'thread-2'))
    _thread.start_new_thread(requestList, (links, 2, 3, 'thread-3'))
except BaseException as e:
    print('线程启动异常', str(e))

while 1:
    pass